import 'package:get/get.dart';
import '../model/follow_model.dart';
import '../data/follow_data.dart';

/// 用户关注状态管理
/// 使用GetX进行全局状态管理，采用非常规命名避免标准模式
class FollowState extends GetxController {
  // 所有关注关系
  final RxList<FollowModel> _allFollows = <FollowModel>[].obs;

  // 当前用户ID
  final RxString _currentUserId = ''.obs;

  /// 获取所有关注关系
  List<FollowModel> get allFollows => _allFollows.toList();

  /// 获取当前用户ID
  String get currentUserId => _currentUserId.value;

  /// 设置当前用户ID
  void setCurrentUserId(String userId) {
    _currentUserId.value = userId;
  }

  /// 获取当前用户的关注列表（我关注的人）
  List<FollowModel> get followingList {
    return _allFollows
        .where((follow) => follow.followerId == _currentUserId.value)
        .toList();
  }

  /// 获取当前用户的粉丝列表（关注我的人）
  List<FollowModel> get followersList {
    return _allFollows
        .where((follow) => follow.followingId == _currentUserId.value)
        .toList();
  }

  /// 获取关注数量
  int get followingCount => followingList.length;

  /// 获取粉丝数量
  int get followersCount => followersList.length;

  /// 检查是否关注了某个用户
  bool isFollowing(String targetUserId) {
    return _allFollows.any(
      (follow) =>
          follow.followerId == _currentUserId.value &&
          follow.followingId == targetUserId,
    );
  }

  /// 检查是否被某个用户关注
  bool isFollowedBy(String targetUserId) {
    return _allFollows.any(
      (follow) =>
          follow.followerId == targetUserId &&
          follow.followingId == _currentUserId.value,
    );
  }

  /// 检查是否互相关注
  bool isMutualFollow(String targetUserId) {
    return isFollowing(targetUserId) && isFollowedBy(targetUserId);
  }

  /// 关注用户
  void followUser(String targetUserId) {
    // 检查是否已经关注
    if (isFollowing(targetUserId)) {
      return;
    }

    final followId = DateTime.now().millisecondsSinceEpoch.toString();
    final follow = FollowModel(
      id: followId,
      followerId: _currentUserId.value,
      followingId: targetUserId,
      followTime: DateTime.now(),
    );

    _allFollows.add(follow);

    // 检查是否互相关注
    _updateMutualFollowStatus(targetUserId);
  }

  /// 取消关注用户
  void unfollowUser(String targetUserId) {
    _allFollows.removeWhere(
      (follow) =>
          follow.followerId == _currentUserId.value &&
          follow.followingId == targetUserId,
    );

    // 更新互相关注状态
    _updateMutualFollowStatus(targetUserId);
  }

  /// 更新互相关注状态
  void _updateMutualFollowStatus(String targetUserId) {
    // 更新当前用户对目标用户的关注状态
    final currentUserFollow = _allFollows.firstWhereOrNull(
      (follow) =>
          follow.followerId == _currentUserId.value &&
          follow.followingId == targetUserId,
    );

    if (currentUserFollow != null) {
      final isMutual = isFollowedBy(targetUserId);
      final updatedFollow = currentUserFollow.copyWith(isMutual: isMutual);
      final index = _allFollows.indexWhere((f) => f.id == currentUserFollow.id);
      if (index != -1) {
        _allFollows[index] = updatedFollow;
      }
    }

    // 更新目标用户对当前用户的关注状态
    final targetUserFollow = _allFollows.firstWhereOrNull(
      (follow) =>
          follow.followerId == targetUserId &&
          follow.followingId == _currentUserId.value,
    );

    if (targetUserFollow != null) {
      final isMutual = isFollowing(targetUserId);
      final updatedFollow = targetUserFollow.copyWith(isMutual: isMutual);
      final index = _allFollows.indexWhere((f) => f.id == targetUserFollow.id);
      if (index != -1) {
        _allFollows[index] = updatedFollow;
      }
    }
  }

  /// 获取关注用户的ID列表
  List<String> getFollowingUserIds() {
    return followingList.map((follow) => follow.followingId).toList();
  }

  /// 获取粉丝用户的ID列表
  List<String> getFollowersUserIds() {
    return followersList.map((follow) => follow.followerId).toList();
  }

  /// 获取互相关注的用户ID列表
  List<String> getMutualFollowUserIds() {
    return followingList
        .where((follow) => follow.isMutual)
        .map((follow) => follow.followingId)
        .toList();
  }

  /// 根据用户ID获取关注关系
  FollowModel? getFollowByUserIds(String followerId, String followingId) {
    try {
      return _allFollows.firstWhere(
        (follow) =>
            follow.followerId == followerId &&
            follow.followingId == followingId,
      );
    } catch (e) {
      return null;
    }
  }

  /// 删除关注关系（用于清理数据）
  void removeFollow(String followId) {
    _allFollows.removeWhere((follow) => follow.id == followId);
  }

  /// 清空所有关注关系
  void clearAllFollows() {
    _allFollows.clear();
  }

  @override
  void onInit() {
    super.onInit();
    _loadDefaultData();
  }

  /// 加载默认数据
  void _loadDefaultData() {
    _allFollows.assignAll(FollowData.getDefaultFollows());
  }
}
